/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent, Fragment } from "react";
import { connect } from "dva";
import { Button, Input, Form, Row, Col, message, Modal } from "antd";
import router from "umi/router";

const FormItem = Form.Item;
const { confirm } = Modal;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 9 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 10 },
    md: { span: 6 },
  },
};

const submitFormLayout = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 10, offset: 9 },
  },
};
@connect(({ loading, account }) => ({
  account,
  bindLoading: loading.effects["account/bindAccount"],
}))
@Form.create()
export default class Account extends PureComponent {
  state = {
    currentPage: 1,
    second: 60,
  };

  getSmsCode = () => {
    const {
      dispatch,
      account: { phone },
    } = this.props;
    dispatch({
      type: "account/getSmsCode",
      payload: {
        phone,
        send: 1,
      },
      then: () => {
        this.setInterval();
      },
    });
  };

  setTimers = (ts, timerStart = true) => {
    this.setState({
      timerStart,
      second: ts,
    });
  };

  setInterval = () => {
    let second = 60;

    this.setTimers(second);
    this.timer = setInterval(() => {
      if (second > 0) {
        second--;
        this.setTimers(second);
      } else {
        this.clearInterval();
      }
    }, 1000);
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      onSwitchTab,
      form: { validateFields, resetFields },
      dispatch,
      account: { phone },
    } = this.props;
    validateFields(["code", "alipay_account", "alipay_name"], (err, values) => {
      if (err) {
        return;
      }
      dispatch({
        type: "account/bindAccount",
        payload: {
          ...values,
          phone,
          send: 1,
        },
        then: (code, msg) => {
          if (code == 0) {
            message.success("绑定成功");
            this.clearInterval();
            resetFields();
            if (onSwitchTab) {
              onSwitchTab("0");
            }
            router.replace("/finance/account#0");
          } else {
            message.error(msg);
          }
        },
      });
    });
  };

  clearInterval = () => {
    this.timer && clearInterval(this.timer);
    this.setTimers(60, false);
  };

  // 取消绑定
  handleCancelBind = () => {
    const { dispatch } = this.props;
    confirm({
      title: "温馨提示",
      content: "确定要解绑吗？",
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        dispatch({
          type: "account/bindAccount",
          payload: "",
          then: (code, msg) => {
            if (code == 0) {
              message.success("已解除绑定");
            } else {
              message.error(msg);
            }
          },
        });
      },
    });
  };

  componentWillUnmount() {
    this.clearInterval();
  }

  render() {
    const {
      form,
      account: { phone, info },
      bindLoading,
    } = this.props;
    const { getFieldDecorator } = form;
    const { second, timerStart } = this.state;
    const { alipay_name, alipay_account } = info || {};
    return (
      <Fragment>
        {alipay_name ? (
          <div>
            <FormItem {...formItemLayout} label="支付宝账户">
              {alipay_account}
            </FormItem>
            <FormItem {...formItemLayout} label="支付宝姓名">
              {alipay_name}
            </FormItem>
            <FormItem {...formItemLayout} label="目前状态">
              <span style={{ color: "orange" }}>已绑定</span>
            </FormItem>
            <FormItem {...submitFormLayout}>
              <Button type="primary" loading={bindLoading} onClick={this.handleCancelBind}>
                取消绑定
              </Button>
            </FormItem>
          </div>
        ) : (
          <Form onSubmit={this.handleSubmit} className="mtb-30">
            <FormItem {...formItemLayout} label="登录手机号">
              <Row gutter={8}>
                <Col span={12}>
                  <span className="c-gray">
                    {/*{phone && phone.replace(/(\d{3})(\d{4})(\d{4})/g, "$1 xxxx $3")}*/}
                    {phone}
                  </span>
                </Col>
                <Col span={12} className="flex-row" style={{ justifyContent: "flex-end" }}>
                  {!timerStart ? (
                    <Button type="primary" onClick={this.getSmsCode}>
                      获取验证码
                    </Button>
                  ) : (
                    <Button type="primary" disabled>
                      {second}s
                    </Button>
                  )}
                </Col>
              </Row>
            </FormItem>
            <FormItem {...formItemLayout} label="验证码">
              {getFieldDecorator("code", {
                rules: [{ required: true, message: "请输入验证码" }],
              })(<Input style={{ width: "100%" }} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="支付宝账户">
              {getFieldDecorator("alipay_account", {
                rules: [
                  { required: true, message: "请输入支付宝账户" },
                  {
                    pattern: /\w+[@]{1}\w+[.]\w+|^1\d{10}$/,
                    message: "支付宝账户只能位邮箱或者手机号",
                  },
                ],
              })(<Input style={{ width: "100%" }} />)}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="支付宝姓名"
              extra={
                <span style={{ color: "#f00" }}>
                  支付宝姓名为对应支付宝账号实名认证姓名，维护错误将导致无法正常提现！
                </span>
              }
            >
              {getFieldDecorator("alipay_name", {
                rules: [{ required: true, message: "请输入支付宝姓名" }],
              })(<Input style={{ width: "100%" }} />)}
            </FormItem>
            <FormItem {...submitFormLayout}>
              <Button type="primary" htmlType="submit" loading={bindLoading}>
                绑定
              </Button>
              <p>绑定成功后，即可随时从快宝智慧快递管理平台提现到绑定的支付宝账号。</p>
            </FormItem>
          </Form>
        )}
      </Fragment>
    );
  }
}
